<template>
  <el-form ref="form" :model="form" :rules="rules" size="small" class="bold-label">
    <el-form-item label="手机号" prop="phone" ref="phone">
      <el-input :value="form.phone" :disabled="true" />
    </el-form-item>
    <el-form-item label="新密码" prop="password" ref="password">
      <el-input v-model="form.password" placeholder="请输入密码" show-password />
    </el-form-item>
    <el-form-item label="密码确认" prop="rePassword" ref="rePassword">
      <el-input v-model="form.rePassword" placeholder="请再次输入密码" show-password />
    </el-form-item>
    <el-form-item label="验证码" prop="code" ref="code">
      <el-input v-model="form.code" placeholder="请输入验证码" @keyup.enter.native="onSubmit">
        <send-code-btn
          slot="suffix"
          :phone="form.phone"
          @checkPhone="checkPhone"
          class="m-r-10"
        />
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" :loading="loading">保存密码</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapActions } from 'vuex';
import SendCodeBtn from '@/components/shared/SendCodeBtn';

export default {
  name: 'ResetPasswordForm', // 账户设置的修改密码
  components: { SendCodeBtn },
  data() {
    return {
      form: {
        phone: this.$store.state.currentUser.phone, // 手机号
        password: '', // 密码
        rePassword: '', // 确认密码
        code: '', // 验证码
      },
      rules: {
        phone: [{ required: true, validator: this.$va.phone, trigger: 'blur' }],
        password: [{ required: true, validator: this.$va.password, trigger: ['blur', 'change'] }],
        rePassword: [{ required: true, validator: this.$va.rePassword, trigger: ['blur', 'change'] }],
        code: [{ required: true, validator: this.$va.code, trigger: 'blur' }],
      },
      loading: false, // 是否正在保存密码
    };
  },
  methods: {
    ...mapActions({ removeCurUser: 'removeCurrentUser' }),
    // 提交表单
    onSubmit() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.loading = true;
          this.$api.users.signUp(this.form)
            .then(() => {
              this.$message.success('密码修改成功，请用新密码登录');
              this.removeCurUser();
              this.$router.push('/users/sign_in');
            })
            .catch(() => {})
            .then(() => { this.loading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 触发验证手机号
    checkPhone() { this.$refs.form.validateField('phone'); },
  },
};
</script>

<style></style>
